//
//  DarkTool.m
//  GMNHeaderFile
//
//  Created by mac on 15/12/29.
//  Copyright © 2015年 gmn_dark. All rights reserved.
//

#import "DarkTool.h"

@implementation DarkTool
// IOS 开发中判断字符串是否为空字符的方法
//也仅适用于NSString
+ (BOOL) isBlankString:(id)string {
    if(![string isKindOfClass:[NSString class]])
    {
        return YES;
    }
    else if(string == nil)
    {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    if ([string isEqualToString:@"(null)"])
    {
        return YES;
    }
    if ([string isEqualToString:@"<null>"])
    {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0)
    {
        return YES;
    }
    return NO;
}

// 整形判断
+ (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

//获取设备分辨率
+ (NSString *) getDeviceResolution{
    
    CGRect rect_screen = [[UIScreen mainScreen]bounds];
    CGSize size_screen = rect_screen.size;
    
    //获得scale：
    CGFloat scale_screen = [UIScreen mainScreen].scale;
    
    //获取分辨率
    CGFloat width = size_screen.width*scale_screen;
    CGFloat height = size_screen.height*scale_screen;
    
    NSString *str = [NSString stringWithFormat:@"%0.0f*%0.0f",width,height];
    return str;
}


//获取设备语言
+ (NSString*)getPreferredLanguage{
    
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    
    NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];
    
    NSString * preferredLang = [allLanguages objectAtIndex:0];
    //en是英语，zh-Hans是简体中文，zh-Hant是繁体中文
    NSLog(@"当前语言:%@", preferredLang);
    
    return preferredLang;
    
}

//获取版本号
+ (NSString *) getApp_version
{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    
    //获得build号：
    //return [infoDic objectForKey:@"CFBundleVersion"];
    //Verison号：
    return [infoDic objectForKey:@"CFBundleShortVersionString"];
}

+ (CGFloat)getIosVersion {
    return [[[UIDevice currentDevice] systemVersion] floatValue];
}

//判断手机号是否正确
+(BOOL) isValidateMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:mobile];
}

//邮箱验证 MODIFIED BY HELENSONG
+(BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//取数组中的最大的一个元素
+(NSString*)MaxValueFromArray:(NSMutableArray *)mutableArray
{
    //取得两个值比较大的一个
    NSComparator cmptr = ^(id obj1, id obj2){
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    };
    
    NSArray *array = [mutableArray sortedArrayUsingComparator:cmptr];
    NSString *max = [array lastObject];
    
    return max;
    
}

#pragma mark 关于网络请求相关的一些视图操作
//移除加载中状态视图
+ (void)removeLoadingView:(UIView *)view{
    [[view viewWithTag:1000]removeFromSuperview];
    view = nil;
}

//移除为空视图
+ (void)removeNullView:(UIView *)view{
    [[view viewWithTag:1001]removeFromSuperview];
    view = nil;
}

//移除失败视图
+ (void)removeErrorView:(UIView *)view{
    [[view viewWithTag:1002]removeFromSuperview];
    view = nil;
}

//请求数据加载中
+ (void)addLoadinView:(UIView *)view
               center:(CGPoint)point{
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityView.tag = 1000;
    activityView.frame = CGRectMake(0,0, kTopBarHeight, kTopBarHeight);
    [activityView startAnimating];
    [view addSubview:activityView];
    [activityView setCenter:point];
    
    UILabel *bgLabel = [[UILabel alloc]initWithFrame:CGRectMake(-activityView.frame.origin.x, activityView.frame.size.height , GMN_kScreenWidth, 20)];
    bgLabel.backgroundColor = [UIColor clearColor];
    bgLabel.textColor  = [UIColor lightGrayColor];
    bgLabel.text = @"正在加载";
    bgLabel.textAlignment = NSTextAlignmentCenter;
    [activityView addSubview:bgLabel];
}

//添加请求数据为空视图
+ (void)addNullView:(UIView *)view
             center:(CGPoint)point
          imageName:(NSString *)imageName
              title:(NSString *)titleString{
    //TODO: 晚点等为空视图出来后再对视图的宽高重新设置
    UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, GMN_kScreenWidth*140/2/320, GMN_kScreenHeight*140/2/320)];
    bgImageView.tag = 1001;
    bgImageView.image = [UIImage imageNamed:imageName];
    [view addSubview:bgImageView];
    [bgImageView setCenter:CGPointMake(point.x, point.y)];
    
    UILabel *bgLabel = [[UILabel alloc]initWithFrame:CGRectMake(-bgImageView.frame.origin.x,bgImageView.frame.size.height + 10, GMN_kScreenWidth, 30)];
    bgLabel.backgroundColor = [UIColor clearColor];
    bgLabel.text = titleString;
    bgLabel.textAlignment = NSTextAlignmentCenter;
    [bgImageView addSubview:bgLabel];
    
    
}

//添加请求失败再次刷新视图
+ (void)addErrorView:(UIView *)view
              center:(CGPoint)point
               title:(NSString *)titleString
              target:(id)target
            selector:(SEL)action
{
    //TODO: 等UI设计好后需要修改error视图大小和图片名字，还有文字
    UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, GMN_kScreenWidth*140/2/320, GMN_kScreenHeight*140/2/320)];
    bgImageView.tag = 1002;
    bgImageView.image = [UIImage imageNamed:@"netWorkError"];
    [view addSubview:bgImageView];
    [bgImageView setCenter:point];
    
    UILabel *bgLabel = [[UILabel alloc]initWithFrame:CGRectMake(-bgImageView.frame.origin.x,bgImageView.frame.size.height + 10, GMN_kScreenWidth, 30)];
    bgLabel.backgroundColor = [UIColor clearColor];
    //    bgLabel.text = titleString;
    //
    //    if([titleString isEqualToString:@"visit over frequently,slow down !"])
    bgLabel.text = @"请求失败，请重新加载";
    
    bgLabel.textAlignment = NSTextAlignmentCenter;
    [bgImageView addSubview:bgLabel];
    
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]initWithTarget:target action:action];
    bgImageView.userInteractionEnabled = YES;
    bgLabel.userInteractionEnabled = YES;
    [bgImageView addGestureRecognizer:gesture];
}


/**
 *  字典 转 json
 *
 *  @param dic 字典
 *
 *  @return json
 */
+ (NSString *)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    
}

/**
 *  json 转字典
 *
 *  @param jsonString json
 *
 *  @return 字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    
    if(err) {
        
        NSLog(@"json解析失败：%@",err);
        
        return nil;
        
    }
    
    return dic;
    
}

//将字典转换成字符串 key=value&key=value&key=value
+ (NSString *)parseDictionaryToFormattedString:(NSDictionary *)paramsDic;
{
    NSMutableArray *tempArray = [NSMutableArray array];
    NSArray *keyArray = [paramsDic allKeys];
    for (NSString *key in keyArray) {
        NSString *valueString = [paramsDic objectForKey:key];
        NSString *formattedString = [NSString stringWithFormat:@"%@=%@", key, valueString];
        [tempArray addObject:formattedString];
    }
    NSString *finalString = [tempArray componentsJoinedByString:@"&"];
    return finalString;
}
//添加请求数据为空视图
+ (void)addNullView:(UIView *)view
             center:(CGPoint)point
          imageName:(NSString *)imageName
              title:(NSString *)titleString
      withImageSize:(CGSize)imageSize
{
    if(imageSize.height == 0)
    {
        imageSize = CGSizeMake(300, 300);
    }
    //TODO: 晚点等为空视图出来后再对视图的宽高重新设置
    UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, GMN_kScreenWidth*imageSize.width/2/320, GMN_kScreenHeight*imageSize.height/2/320)];
    bgImageView.tag = 1001;
    bgImageView.image = [UIImage imageNamed:imageName];
    [view addSubview:bgImageView];
    [bgImageView setCenter:CGPointMake(point.x, point.y)];
    bgImageView.contentMode = UIViewContentModeScaleAspectFit;
    
    
    
    UILabel *bgLabel = [[UILabel alloc]initWithFrame:CGRectMake(-bgImageView.frame.origin.x,bgImageView.frame.size.height + 10, GMN_kScreenWidth, 30)];
    bgLabel.backgroundColor = [UIColor clearColor];
    bgLabel.text = titleString;
    bgLabel.textColor = [UIColor blueColor];
    bgLabel.textAlignment = NSTextAlignmentCenter;
    [bgImageView addSubview:bgLabel];
    
    
}

@end
